package com.atguigu.tingshu.album.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.atguigu.tingshu.album.config.MinioConstantProperties;
import com.atguigu.tingshu.album.service.FileUploadService;
import com.atguigu.tingshu.common.execption.GuiguException;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;

/**
 * Package: com.atguigu.tingshu.album.service.impl
 *
 * @author xiongkunYang
 * @description:
 * @since 2025/6/14 10:44
 */
@Slf4j
@Service
public class FileUploadServiceImpl implements FileUploadService {

    private final MinioClient minioClient;
    private final MinioConstantProperties minioProps;

    public FileUploadServiceImpl(MinioClient minioClient, MinioConstantProperties minioProps) {
        this.minioClient = minioClient;
        this.minioProps = minioProps;
    }

    /**
     * 将图片文件上传到 minio
     *
     * @param file 图片文件
     * @return 上传后图片在线地址
     */
    @Override
    public String fileUpload(MultipartFile file) {
        try {
            // 业务校验验证文件是否为图片，借助ImageIO读取图片
            BufferedImage read = ImageIO.read(file.getInputStream());
            if (read == null) {
                throw new GuiguException(400, "图片格式非法！");
            }

            //2.调用 minio-Java客户端对象将文件上传到 minio
            String folderName = "/" + DateUtil.today() + "/";
            String originalName = file.getOriginalFilename();
            String extName = FileUtil.extName(originalName);
            String fileName = IdUtil.randomUUID() + originalName + "." + extName;
            //2.2 调用文件上传接口
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(minioProps.getBucketName())
                    .object(folderName + fileName)
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .contentType(file.getContentType())
                    .build());

            // 拼接上传文件成功后在线地址 http://ip:9000/存储空间名称/路径/文件标识名称
            return minioProps.getEndpointUrl() + "/" + minioProps.getBucketName() + folderName + fileName;
        } catch (Exception e) {
            log.error("[专辑服务]上传图片文件异常：{}", e.getMessage(), e);
            throw new RuntimeException(e);
        }
    }
}